
package com.xiaoma.myaudience.biz.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import cn.sharesdk.framework.AbstractWeibo;
import cn.sharesdk.onekeyshare.ShareAllGird;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.app.AudienceApplication;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.util.Logger;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;

/**
 * 个人中心页面.
 * 
 * @author xali
 */
public class PersonalCenterActivity extends BaseActivity {
	
	private static final int MENU_LOGIN = Menu.FIRST;
	private static final int MENU_LOGOUT = MENU_LOGIN + 1;
	private static final int MENU_GROUP_LOGIN = Menu.FIRST;
	private static final int MENU_GROUP_LOGOUT = MENU_GROUP_LOGIN + 1;
	
	private Context mContext;
	
	private RelativeLayout mPersonalLayout;//个人资料
	private RelativeLayout mChangePwdLayout;
	private RelativeLayout mMyCollectLayout;//消息提醒
	
	
	private RelativeLayout mFeedBackLayout;
	private RelativeLayout mSharefriendslayout;
	private RelativeLayout mSettingLayout;//about
	private Button mLogoutButton;
	private RelativeLayout mPersonLogoutLayout;//about
	private RelativeLayout mPersontologinLayout;//tologin
	private RelativeLayout mPersontoregisterLayout;//toregister
	private LinearLayout mPersonunloginedLayout;//已登录
	private LinearLayout mPersonloginedLayout;//未登录
	private static Boolean bJpushswitch  =true;
	public static String TEST_IMAGE;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.personal_center_activity);
        
        setNetEaseTitleBarVisibility(View.VISIBLE);
        setNetEaseTitle(R.string.title_personal_center);
        setNetEaseTitleGravity(Gravity.CENTER);
        
        mContext = this;
        
        findView();
        setlayoutClickListener();
        if(!CheckIsLogin()){
        	mPersonunloginedLayout.setVisibility(View.VISIBLE);
        	mPersonloginedLayout.setVisibility(View.GONE);
        	mPersonLogoutLayout.setVisibility(View.GONE);
        }else{
        	mPersonLogoutLayout.setVisibility(View.VISIBLE);
        	mPersonloginedLayout.setVisibility(View.VISIBLE);
        	mPersonunloginedLayout.setVisibility(View.GONE);
        }
        
        initImagePath();
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
        if(!CheckIsLogin()){
        	mPersonunloginedLayout.setVisibility(View.VISIBLE);
        	mPersonloginedLayout.setVisibility(View.GONE);
        	mPersonLogoutLayout.setVisibility(View.GONE);
        }else{
        	mPersonLogoutLayout.setVisibility(View.VISIBLE);
        	mPersonloginedLayout.setVisibility(View.VISIBLE);
        	mPersonunloginedLayout.setVisibility(View.GONE);
        }
    }
    
    @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
    	Boolean bi = CheckIsLogin();
        if(!bi){
        	mPersonunloginedLayout.setVisibility(View.VISIBLE);
        	mPersonloginedLayout.setVisibility(View.GONE);
        	mPersonLogoutLayout.setVisibility(View.GONE);
        }else{
        	mPersonLogoutLayout.setVisibility(View.VISIBLE);
        	mPersonloginedLayout.setVisibility(View.VISIBLE);
        	mPersonunloginedLayout.setVisibility(View.GONE);
        }
    }
    //检查是否登录
	private Boolean CheckIsLogin(){
		// TODO Auto-generated method stub
		Boolean islogin = PrefHelper.getBoolean(PersonalCenterActivity.this,Constant.LOGIN_ISLOGIN, false);
    	if(islogin){
	        	Logger.e("xxx登录 了mUsername:");
        			//check the expriedate
        			String loginexprie = PrefHelper.getString(this, Constant.LOGIN_EXPIRESDATE, null);
        			if(loginexprie==null) return false;
        			Date expiretime;
						expiretime = new Date(loginexprie);
						int c=expiretime.compareTo(new Date());
						if(c>=0){
						   //cookie未过期
							islogin = true;
						}else{
							islogin = false;
						}
    	}
    	return islogin;
	}
    /**设置组件监听动作*/
	private void setlayoutClickListener() {
			
			//绑定登录
			mPersontologinLayout.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					Intent intent = new Intent(mContext, LoginActivity.class);
					startActivity(intent);
				}
			});
			
			mPersontoregisterLayout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(mContext, RegisterActivity.class);
					startActivity(intent);
				}
			});
			
			
			mLogoutButton.setOnClickListener(new OnClickListener() {	
				@Override
				public void onClick(View v) {
					PrefHelper.putBoolean(PersonalCenterActivity.this,Constant.LOGIN_ISLOGIN,false);
					PrefHelper.putBoolean(PersonalCenterActivity.this,"ischeckedupdate",false);
					mPersonLogoutLayout.setVisibility(View.GONE);
					
		        	mPersonloginedLayout.setVisibility(View.GONE);
		        	mPersonunloginedLayout.setVisibility(View.VISIBLE);
		    		PrefHelper.putString(PersonalCenterActivity.this,Constant.LOGIN_EXPIRESDATE,"");
		    		PrefHelper.putString(PersonalCenterActivity.this,Constant.LOGIN_COOKIE1,"");
		    		PrefHelper.putString(PersonalCenterActivity.this,Constant.LOGIN_COOKIE2,"");
				}
			});
		
		mPersonalLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {

	        		Logger.e("登录");
	        		Intent intent = new Intent(mContext, LoginActivity.class);
					startActivity(intent);
			}
		});
		 

		
		mChangePwdLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Intent intent = new Intent(mContext, ChangePwdLayout.class);
				//startActivity(intent);
				if(CheckIsLogin()){
					Intent intent = new Intent(PersonalCenterActivity.this,EditUserInfoActivity.class);
					intent.putExtra("code", "1");
					intent.putExtra("name", "密码");
					startActivity(intent);
				}else{
					Tips("请先登录.");
				}
			}
		});
		
		mMyCollectLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(PersonalCenterActivity.this, MyPushServiceSwitchActivity.class);
				startActivity(i);
			}
		});
		
		mFeedBackLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, FeedBackActivity.class);
				startActivity(intent);
			}
		});
		
		mSharefriendslayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showGrid(false);
			}
		});
		mSettingLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, AboutActivity.class);
				startActivity(intent);
			}
		});
		
		
	}

	/**初始化组件*/
	private void findView() {
		// TODO Auto-generated method stub
		mPersonalLayout = (RelativeLayout)findViewById(R.id.rel_personal_layout);
		mChangePwdLayout = (RelativeLayout)findViewById(R.id.rel_changepwd_layout);
		mMyCollectLayout = (RelativeLayout)findViewById(R.id.rel_mycollect_layout);

		mFeedBackLayout = (RelativeLayout)findViewById(R.id.rel_feedback_layout);
		mSharefriendslayout = (RelativeLayout)findViewById(R.id.rel_sharefriends_layout);
		mSettingLayout = (RelativeLayout)findViewById(R.id.rel_setting_layout);
		
		mLogoutButton=(Button)findViewById(R.id.btn_personal_logoutx);
		mPersonLogoutLayout=(RelativeLayout)findViewById(R.id.rel_personal_logoutx);
		mPersonloginedLayout=(LinearLayout)findViewById(R.id.personal_logined_layout);
		mPersonunloginedLayout=(LinearLayout)findViewById(R.id.personal_unlogined_layout);
		mPersontologinLayout=(RelativeLayout)findViewById(R.id.rel_tologin_layout);
		mPersontoregisterLayout=(RelativeLayout)findViewById(R.id.rel_toregister_layout);
	}
	
	@Override
    public boolean onCreateOptionsNeteaseMenu(Menu menu) {
//		((VideoMainActivity)getParent()).onCreateOptionsNeteaseMenu(menu);
		
//		 menu.add(MENU_GROUP_LOGIN, MENU_LOGIN, 0, R.string.menu_login).setIcon(R.drawable.ic_menu_login);
//		 menu.add(MENU_GROUP_LOGOUT, MENU_LOGOUT, 0, R.string.menu_logout).setIcon(R.drawable.ic_menu_login);
		
        return true;
    }
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		boolean isLogin = ((AudienceApplication)getApplication()).isLogin();
//		menu.setGroupVisible(MENU_GROUP_LOGIN, !isLogin);
//		menu.setGroupVisible(MENU_GROUP_LOGOUT, isLogin);
		return super.onPrepareOptionsMenu(menu);
	}

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
//    	if (!((VideoMainActivity) getParent()).onMenuItemSelected(featureId, item)) {
//    		
//	    	switch (item.getItemId()) {
//			case MENU_LOGIN:
//				startActivity(new Intent(this, LoginActivity.class));
//				break;
//			case MENU_LOGOUT:
//				
//				((VideoApplication)getApplication()).postExe(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//						ContentResolver resolver = getContentResolver();
//	            		Uri uri = UserAccountDbHelper.getUri();
//	    				ContentValues values = new ContentValues();
//	    		    	values.put(UserAccount.ISLOGIN, "0");
//	    		    	String whereString = String.format("%s%s", UserAccount.ISLOGIN, " =?"); 
//	    		    	String selectaionArgs[] = {"1"};
//	    		    	resolver.update(uri, values, whereString, selectaionArgs);
//					}
//				});
//				
//				break;
//			default:
//				break;
//			}
//	    	
//    	}
        return true;
    }
	
    
    /**
	 * 使用快捷分享完成图文分享
	 */
	private void showGrid(boolean silent) {
		Intent i = new Intent(this, ShareAllGird.class);
		// 分享时Notification的图标
		i.putExtra("notif_icon", R.drawable.icon);
		// 分享时Notification的标题
		i.putExtra("notif_title", this.getString(R.string.app_name));

		// title标题，在印象笔记、邮箱、信息、微信（包括好友和朋友圈）、人人网和QQ空间使用，否则可以不提供
		i.putExtra("title", this.getString(R.string.share));
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用，否则可以不提供
		i.putExtra("titleUrl", "http://sharesdk.cn");
		// text是分享文本，所有平台都需要这个字段
		i.putExtra("text", this.getString(R.string.share_content));
		// imagePath是本地的图片路径，所有平台都支持这个字段，不提供，则表示不分享图片
		i.putExtra("imagePath", PersonalCenterActivity.TEST_IMAGE);
		// url仅在微信（包括好友和朋友圈）中使用，否则可以不提供
		i.putExtra("url", "http://sharesdk.cn");
		// thumbPath是缩略图的本地路径，仅在微信（包括好友和朋友圈）中使用，否则可以不提供
		i.putExtra("thumbPath", PersonalCenterActivity.TEST_IMAGE);
		// appPath是待分享应用程序的本地路劲，仅在微信（包括好友和朋友圈）中使用，否则可以不提供
		i.putExtra("appPath", PersonalCenterActivity.TEST_IMAGE);
		// comment是我对这条分享的评论，仅在人人网和QQ空间使用，否则可以不提供
		i.putExtra("comment", this.getString(R.string.share));
		// site是分享此内容的网站名称，仅在QQ空间使用，否则可以不提供
		i.putExtra("site", this.getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用，否则可以不提供
		i.putExtra("siteUrl", "http://www.iguanzhong.cn");

		// 是否直接分享
		i.putExtra("silent", silent);
		this.startActivity(i);
	}
	
	/**
	 * 将action转换为String
	 */
	public static String actionToString(int action) {
		switch (action) {
			case AbstractWeibo.ACTION_AUTHORIZING: return "ACTION_AUTHORIZING";
			case AbstractWeibo.ACTION_GETTING_FRIEND_LIST: return "ACTION_GETTING_FRIEND_LIST";
			case AbstractWeibo.ACTION_FOLLOWING_USER: return "ACTION_FOLLOWING_USER";
			case AbstractWeibo.ACTION_SENDING_DIRECT_MESSAGE: return "ACTION_SENDING_DIRECT_MESSAGE";
			case AbstractWeibo.ACTION_TIMELINE: return "ACTION_TIMELINE";
			case AbstractWeibo.ACTION_USER_INFOR: return "ACTION_USER_INFOR";
			case AbstractWeibo.ACTION_SHARE: return "ACTION_SHARE";
			default: {
				return "UNKNOWN";
			}
		}
	}
	
	
	/**
	 * 初始化分享的图片
	 */
	private void initImagePath() {
		try {//判断SD卡中是否存在此文件夹
			if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
					&& Environment.getExternalStorageDirectory().exists()) {
				TEST_IMAGE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/pic.png";
			}
			else {
				TEST_IMAGE = getApplication().getFilesDir().getAbsolutePath() + "/pic.png";
			}
			File file = new File(TEST_IMAGE);
			//判断图片是否存此文件夹中
			if (!file.exists()) {
				file.createNewFile();
				Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
				FileOutputStream fos = new FileOutputStream(file);
				pic.compress(CompressFormat.JPEG, 100, fos);
				fos.flush();
				fos.close();
			}
		} catch(Throwable t) {
			t.printStackTrace();
			TEST_IMAGE = null;
		}
	}
	
}
